package com.anbinh.doctor.fragment.account;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.anbinh.doctor.DetailtActivity;
import com.anbinh.doctor.R;
import com.anbinh.doctor.adapter.ServiceChildAdapter;
import com.anbinh.doctor.model.DataResponse;
import com.anbinh.doctor.model.ResponseServices;
import com.anbinh.doctor.model.ResponseServices.Item;
import com.anbinh.doctor.model.UserLogin;
import com.anbinh.doctor.request.controller.ServerController;
import com.anbinh.doctor.service.request.OnRequest;
import com.anbinh.doctor.utils.Utils;
import com.lsjwzh.widget.materialloadingprogressbar.CircleProgressBar;

public class FragmentListServiceChild extends SherlockFragment {
	private static FragmentListServiceChild fragment = null;
	private View mView;
	private CircleProgressBar loadding;
	private UserLogin userLogin;
	private ListView mGridView;
	private Item currentService;
	private List<Item> mListService = null;
	private ServiceChildAdapter adapter;
	private List<Item> mListChecked = null;

	public static FragmentListServiceChild newInstance() {
		if (fragment == null) {
			fragment = new FragmentListServiceChild();
		}
		return fragment;
	}

	@Override
	public void onAttach(Activity activity) {
		userLogin = Utils.getAccountModel(getActivity(), Utils.KEY_USER);

		super.onAttach(activity);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
	}

	@Override
	public void onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu,
			com.actionbarsherlock.view.MenuInflater inflater) {
		menu.add(0, R.id.dia_diem_kham, Menu.NONE, "Hoàn thành")
				.setIcon(R.drawable.ic_done)
				.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
		super.onCreateOptionsMenu(menu, inflater);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		List<Item> mList = FragmentListServiceChild.newInstance()
				.getListService();
		if (mList != null && mList.size() > 0) {
			FragmentListServiceChild.newInstance().pushService();
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onResume() {
		super.onResume();
		((DetailtActivity) getActivity()).setActionBarTitle(getResources()
				.getString(R.string.cap_nhat_dich_vu));

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mView = inflater.inflate(R.layout.fragment_message, null);
		mListService = new ArrayList<Item>();
		return mView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		mGridView = (ListView) mView.findViewById(R.id.listView1);
		mGridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				for (int i = 0; i <= mListService.size(); i++) {
					if (position == i) {
						boolean isCheck = !mListService.get(position)
								.isChecked();
						updateUncheck(mListService.get(position).getId(),
								isCheck);
						mListService.get(position).setChecked(isCheck);
					}
				}
				adapter.notifyDataSetChanged();
			}
		});

		loadding = (CircleProgressBar) mView.findViewById(R.id.loadding);
		onLoadService();
	}

	public void updateUncheck(String id, boolean isCheck) {
		for (int i = 0; i < mListChecked.size(); i++) {
			if (id.equals(mListChecked.get(i).getId())) {
				mListChecked.get(i).setChecked(isCheck);
			}
		}
	}

	public List<Item> getListService() {
		return mListService;
	}

	public Item getCurrentService() {
		return currentService;
	}

	public void setListChecked(ResponseServices data) {

		if (data.getData().getItems() == null
				|| data.getData().getItems().size() == 0)
			return;
		mListChecked = new ArrayList<Item>();
		for (int i = 0; i < data.getData().getItems().size(); i++) {
			if (data.getData().getItems().get(i).isChecked()) {
				mListChecked.add(data.getData().getItems().get(i));
				Log.d("List checked", data.getData().getItems().get(i).getId());
			}
		}
	}

	public void onLoadService() {
		loadding.setVisibility(View.VISIBLE);
		ServerController.getInstance(getActivity()).reuquestListServices(
				userLogin.getData().getToken(),
				FragmentListService.newInstance().getCurrentService().getId(),
				new OnRequest<ResponseServices>() {

					@Override
					public void onSuccess(ResponseServices data) {
						setListChecked(data);
						loadding.setVisibility(View.GONE);
						if (data.getResponsecode() >= 0
								&& data.getData() != null
								&& data.getData().getItems() != null
								&& data.getData().getItems().size() > 0) {

							mListService = data.getData().getItems();
							adapter = new ServiceChildAdapter(getActivity(),
									R.layout.seprator_chuyen_khoa, mListService);
							mGridView.setAdapter(adapter);
						}
					}

					@Override
					public void onError(int errorCode, String message) {

					}
				});
	}

	public void pushService() {
		String list = getListSpecial();
		/*
		 * if (list.isEmpty()) { Utils.showMessage(getActivity(),
		 * getResources().getString(R.string.vui_long_chon_dich_vu)); return; }
		 */
		loadding.setVisibility(View.VISIBLE);
		Utils.disableEnableControls(false, mView);
		UserLogin userLogin = Utils.getAccountModel(getActivity(),
				Utils.KEY_USER);
		String token = userLogin.getData().getToken();
		ServerController.getInstance(getActivity()).requestpushService(token,
				list, getListUncheck(), new OnRequest<DataResponse>() {

					@Override
					public void onSuccess(DataResponse data) {
						loadding.setVisibility(View.INVISIBLE);
						Utils.disableEnableControls(true, mView);
						Utils.showMessage(getActivity(), data.getDescription());
						getActivity().finish();
					}

					@Override
					public void onError(int errorCode, String message) {
						loadding.setVisibility(View.INVISIBLE);
						Utils.disableEnableControls(true, mView);
					}

				});
	}

	private String getListUncheck() {
		String result = "";
		if (mListChecked == null)
			return FragmentListService.newInstance().getCurrentService()
					.getId();
		for (int i = 0; i < mListChecked.size(); i++) {
			if (!mListChecked.get(i).isChecked()) {
				result = mListChecked.get(i).getId() + "_" + result;
			}
		}
		if (result.length() > 0) {
			return result.substring(0, result.length() - 1);
		} else {
			return "";
		}

	}

	private String getListSpecial() {
		String result = "";
		for (int i = 0; i < mListService.size(); i++) {
			if (mListService.get(i).isChecked()) {
				result = mListService.get(i).getId() + "_" + result;
			}
		}
		if (result.isEmpty()) {
			return result;
		}
		result = result
				+ FragmentListService.newInstance().getCurrentService().getId();
		return result;

	}

}
